﻿/*
 * ext-helloworld.js
 *
 * Licensed under the Apache License, Version 2
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */
 
/* 
	This is a very basic SVG-Edit extension. It adds a "Hello World" button in
	the left panel. Clicking on the button, and then the canvas will show the
 	user the point on the canvas that was clicked on.
*/
 function HtmlEncode(s)
{
	if (s==null) return s;
	var ret =s.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
	return ret;
}
function HtmlDecode(s)
{    
  	if (s==null) return s;
  	var ret = s.replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&quot;/g, '"').replace(/&amp;/g, '&');    
  	return ret;
};



Ext.require([
		'Ext.data.*',
    'Ext.button.Button',
    'Ext.grid.property.Grid'
]);

 Ext.define('data.datasrc', {
    extend: 'Ext.data.Model',
    fields: ['datasrc', 'bz'] 
});

var store = Ext.create('Ext.data.Store', {
        model: 'data.datasrc',
        autoLoad: true     
    });

var colorSet = Ext.create('Ext.data.Store', {
    fields: ['name'],
    data : [
        {"name":"di_color"},
        {"name":"ai_color"},
        {"name":"caih"}
          ]
});    
    
//
Ext.define('MyApp.view.PropWindow', {
    extend: 'Ext.window.Window',

    height: 690,
    width: 529,
    closable: false,
    title: 'My Window',
    requires: [
        'Ext.grid.plugin.CellEditing',
        'Ext.form.field.Text',
        'Ext.toolbar.TextItem'
    ],  
    setItem:function(data1){
   	m_data={'name':'anim_gen','value':{'src':'','fun':'','colSet':''},'prop':'anim_gen','info':{'src':'','fun':'','colSet':''}}; 
	store.removeAll(false);
    	if(data1!='null')
    	{        
		m_data.name=data1.name;
		m_data.prop=data1.prop;
		if(data1.value!='0') m_data.value=data1.value;
		if(data1.info!=0) m_data.info=data1.info;
	};
	var tagStr=m_data.info.src;
	if(tagStr.length>0)
	{
		var tags=tagStr.split(";");
		var ddStr='[';
		for(i=0;i<tags.length;i++)
		{
			ddStr+='{"datasrc":"'+tags[i]+'","bz":""},';
		}
		ddStr=ddStr.substring(0,ddStr.length-1);
		ddStr+="]";
		var obj =  jQuery.parseJSON(ddStr);    		
		store.loadData(obj,false);
	};	
	Ext.getCmp('fun_text').setValue(m_data.info.fun);  
	Ext.getCmp('colSet').setValue(m_data.info.colSet);  
    	
    },
    initComponent: function() {
        var me = this;
        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
        clicksToEdit: 1
        });
	this.addEvents("ok","cancel");     
        Ext.applyIf(me, {
            items: [
                {
                	  id:'datasrc_grid',
                    xtype: 'gridpanel',
                    height: 200,
                    title: '关联数据',
                    store: store,
                    plugins: [cellEditing],
                    columns: [
                        {                        		
                            xtype: 'gridcolumn',
                            width: 221,
                            dataIndex: 'datasrc',
                            text: '数据源',
                            editor: {   allowBlank: false   }
                        },
                        {
                            xtype: 'gridcolumn',
                            width: 272,
                            dataIndex: 'bz',
                            text: '备注'
                        }
                    ],
                    dockedItems: [{
                				xtype: 'toolbar',
                				items: [{
                    					iconCls: 'icon-add',
                    					text: 'Add',
                    					scope: this,
                    					handler: this.onAddClick
                							}, {
                    					iconCls: 'icon-delete',
                    					text: 'Delete',
                    					itemId: 'delete',
                    					scope: this,
                    					handler: this.onDeleteClick
                							}]
                						}]
                },
                {
                		id:'fun_text',
                    xtype: 'textareafield',
                    height: 180,
                    width: 518,
                    fieldLabel: '逻辑运算'
                },
                {
                    xtype: 'tabpanel',
                    height: 250,
                    activeTab: 0,
                    items: [
                        {
                            xtype: 'panel',
                            height: 200,
                            title: '配色策略',
                            dockedItems: [
                        		{
                            xtype: 'toolbar',
                            dock: 'top',
                            items: [
                                {
                                    xtype: 'combobox',
				    id:'colSet',
                                    fieldLabel: '配色方案',
                                    store:colorSet,
                                    displayField:'name',
                                    valueField:'name',
                                    editable:true,
                                    queryMode:'local',
				    listeners:{
					 scope: this,
					'change': this.onColorSetChg
					}
                                },
                                {
                                    xtype: 'button',
                                    text: '新增'
                                },
                                {
                                    xtype: 'button',
                                    text: '保存'
                                },
                                {
                                    xtype: 'button',
                                    text: '删除'
                                }
                                ,
                                {
                                    xtype: 'button',
                                    text: '+'
                                }
                                ,
                                {
                                    xtype: 'button',
                                    text: '-'
                                }
                                ]
                        		}],
                            items: [
                                   {
                                    xtype: 'gridpanel',
                                    height: 200,
                                    title: '',
                                    columns: [
                                        {
                                            xtype: 'gridcolumn',
                                            dataIndex: 'string',
                                            text: '逻辑运算结果'
                                        },
                                        {
                                            xtype: 'numbercolumn',
                                            dataIndex: 'number',
                                            text: 'Number'
                                        },
                                        {
                                            xtype: 'datecolumn',
                                            dataIndex: 'date',
                                            text: 'Date'
                                        },
                                        {
                                            xtype: 'booleancolumn',
                                            dataIndex: 'bool',
                                            text: 'Boolean'
                                        }
                                    ]
                                    //, plugins: [cellEditing]
                                }
                            ]
                        },
                        {
                            xtype: 'panel',
                            title: '参数设置',
                            items: [
                                {
                                    xtype: 'propertygrid',
                                    height: 200,
                                    title: '',
                                    source: {
                                        'Property 1': 'String',
                                        'Property 2': true,
                                        'Property 3': '2012-05-04T13:07:20',
                                        'Property 4': 123
                                    }
                                }
                            ]
                        }
                    ]
                },
                {
                    xtype: 'button',
                    text: '确定',
                    handler:function(){			
			me.fireEvent('ok');  
                    	me.hide();
                    }
                },
                {
                    xtype: 'button',
                    text: '取消',
                    handler:function(){
			me.fireEvent('cancel');
                    	me.hide();
                    }
                }
            ]
        });
 
        me.callParent(arguments);
    },
    onDeleteClick: function(){  
    	var sm =Ext.getCmp('datasrc_grid').getSelectionModel();
                //cellEditing.cancelEdit();
                store.remove(sm.getSelection());
                if (store.getCount() > 0) {
                    sm.select(0);
                }
    },
    onAddClick: function(){
         
         var r = Ext.create('data.datasrc', {
                    datasrc: '',  bz: ''
                });
                store.add( r);
                cellEditing.startEditByPosition({row: 0, column: 0});
                alert('onAddClick');
    },
    onColorSetChg:function(){
    },
    val:function(){
	var tags=[];
	store.each(function(record) {
		tags.push(record.get('datasrc'));
	});
	
	m_data.info.src=tags.join(";");
	m_data.info.fun=Ext.getCmp('fun_text').getRawValue( );
	m_data.info.colSet=Ext.getCmp('colSet').getRawValue();
	return m_data;
    }
});

Ext.onReady(function(){
  
});

svgEditor.addExtension("Hello World", function() {

			
				//
				function injectHTML() {
				//$('<link rel="stylesheet" type="text/css" href="extensions/sozi/editor.css">').appendTo('head');				
				var html = '<div style="position: relative; top: 220px;left: 10px;display:inline-block;margin: 0px;" id="prop11_div">	<h3 id="prop_Label">属性框</h3>	<div id="prop_div">	</div></div>';
				$(html).insertAfter('#layerpanel');					
				};
				injectHTML() ;
			 
			
	    (function(){
	    	//injectHTML();
				var dlg = Ext.create('MyApp.view.PropWindow');	
				dlg.on('ok',function(){
						var ret=dlg.val();
						var tmp=HtmlEncode(JSON.stringify(ret.info));
						svgCanvas.changeSelectedAttribute(ret.prop,tmp );
						//alert('okkkkk');
				});
					
				$('#prop_div').propertygrid({
				width:200,
				height:300,
				url:'propertygrid_data.json1',
				showGroup:true,
				scrollbarSize:0,
				onDblClickRow:function(rowIndex, rowData){
					if(rowData.group=="动画属性") {
					dlg.setItem(rowData);
					dlg.show();	
					}					
				},
				onAfterEdit:function(rowIndex, rowData, changes){
					if(rowData.group=="交互属性") {
					alert(rowData.name+"--"+rowData.prop+"---"+changes.value);
					svgCanvas.changeSelectedAttribute(rowData.prop,changes.value);
				  }
				}
				});	
				var jsoin = {"total":3,"rows":[	{"name":"Name","value":"caih","group":"prop","editor":"text"}]};
				$('#prop_div').propertygrid("loadData",jsoin);
				

			})();
			
		return {
			name: "Hello World",
			// For more notes on how to make an icon file, see the source of
			// the hellorworld-icon.xml
			svgicons: "extensions/helloworld-icon.xml",
			
			// Multiple buttons can be added in this array
			buttons: [{
				// Must match the icon ID in helloworld-icon.xml
				id: "hello_world", 
				
				// This indicates that the button will be added to the "mode"
				// button panel on the left side
				type: "mode", 
				
				// Tooltip text
				title: "Say 'Hello World'", 
				
				// Events
				events: {
					'click': function() {
						// The action taken when the button is clicked on.
						// For "mode" buttons, any other button will 
						// automatically be de-pressed.
						svgCanvas.setMode("hello_world");
					}
				}
			}],
			// This is triggered when the main mouse button is pressed down 
			// on the editor canvas (not the tool panels)
			mouseDown: function() {
				// Check the mode on mousedown
				if(svgCanvas.getMode() == "hello_world") {
				
					// The returned object must include "started" with 
					// a value of true in order for mouseUp to be triggered
					return {started: true};
				}
			},
			
			// This is triggered from anywhere, but "started" must have been set
			// to true (see above). Note that "opts" is an object with event info
			mouseUp: function(opts) {
				// Check the mode on mouseup
				if(svgCanvas.getMode() == "hello_world") {
					var zoom = svgCanvas.getZoom();
					
					// Get the actual coordinate by dividing by the zoom value
					var x = opts.mouse_x / zoom;
					var y = opts.mouse_y / zoom;
					
					var text = "Hello World!\n\nYou clicked here: " 
						+ x + ", " + y;
						
					// Show the text using the custom alert function
					$.alert(text);
				}
			},
			//caih
			selectedChanged: function(s) { //s.elems, s.selectedElement, s.multiselected
			
				if(s.multiselected) 
				{
				//$("#framelist option:selected").eq(0).attr('selected', false);
				}
				else {
				//Select frame assigned to this selected element
				  var val=1;
					var data='{"total":20,"rows":[';
					var e = s.selectedElement;
					if(s.selectedElement === null) 
					{
						var tmp="1";
						var script= "function begin(){};";//
						script=svgCanvas.getDocScript() ;
						script=script.replace(/[\n]/g,"");
		
						data+='{"name":"画面脚本","value":"'+script+'","group":"画面属性","editor":"textarea","prop":"script","info":"1"},'; //联库信息
						data+='{"name":"背景色","value":'+tmp+',"group":"画面属性","editor":"text","prop":"onclick","info":'+tmp+'}]}';//综合动画			
						//alert(data);	
					}
					else
					{
				  if(e) {
								//add by caih	
					var tmp = e.getAttribute("opacity");
					tmp=HtmlDecode(tmp);val=1;
					if (tmp==null) {tmp=0; val=0;};
					data+='{"name":"透明度","value":'+tmp+',"group":"基本属性","editor":"text","prop":"opacity","info":'+tmp+'},'; //联库信息
					var tmp = e.getAttribute("onclick");
					tmp=HtmlDecode(tmp);val=1;
					if (tmp==null) {tmp=0; val=0;};
					data+='{"name":"左键单击","value":'+tmp+',"group":"交互属性","editor":"textarea","prop":"onclick","info":'+tmp+'},'; //左键单击				
					var tmp = e.getAttribute("anim_moveh");
					tmp=HtmlDecode(tmp);val=1;
					if (tmp==null) {tmp=0; val=0;};
					data+='{"name":"垂直移动","value":'+val+',"group":"动画属性","editor":{"type":"checkbox","options":{"on":1,"off":0}},"prop":"anim_moveh","info":'+tmp+'},'; 
					var tmp = e.getAttribute("anim_movev");
					tmp=HtmlDecode(tmp);val=1;
					if (tmp==null) {tmp=0; val=0;};
					data+='{"name":"水平移动","value":'+val+',"group":"动画属性","editor":{"type":"checkbox","options":{"on":1,"off":0}},"prop":"anim_movev","info":'+tmp+'},';//水平移动
					var tmp = e.getAttribute("anim_gen");
					tmp=HtmlDecode(tmp);val=1;
					if (tmp==null) {tmp=0; val=0;};
					data+='{"name":"综合动画","value":'+val+',"group":"动画属性","editor":{"type":"checkbox","options":{"on":1,"off":0}},"prop":"anim_gen","info":'+tmp+' }]}';//综合动画
				  }					  
				 }
				var obj =  jQuery.parseJSON(data);
				//g_propsGrid.setSource(obj);
				//Ext.getCmp('propsGrid').setItem(selectedElement);
				$('#prop_div').propertygrid("loadData",obj);
		    }
		  },
		  elementChanged : function(o) {
			var elems = o.elems || [];
			if(elems.length === 0) return;

			//TODO: Detect grouped sozi elements (maybe use Array.reduce*)
			$.each(elems, function(i, e) {
			});	
		  },
		  onNewDocument:function(){
		  	/*$.confirm("", function(ok) {
					if(!ok) return;
					
				});*/
		  }

		};
});

